package com.itheima.reggie.controller.EmployeeController;

import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController //resp+ioc
public class EmployeeController {

    //注入service
    @Autowired
    private EmployeeService employeeService;


    //登录
    @PostMapping("/employee/login")         //取出请求体中的参数用map接收     session域一会有用
    public ResultInfo login(@RequestBody Map<String, String> param, HttpSession session) {
        //接收请求参数(参数在map里面)
        String username = param.get("username");
        String password = param.get("password");
        //调用service实现登录(login=登录)
        ResultInfo resultInfo = employeeService.login(username, password);
        //判断是否登录成功
        if (resultInfo.getCode() == 1) {
            // 登录成功
            session.setAttribute(Constant.SESSION_EMPLOYEE, resultInfo.getData());
        }

        //返回ResultInfo
        return resultInfo;
    }

    //退出(这部主要是清理session域中的用户登录信息)
    @PostMapping("/employee/logout")
    public ResultInfo logout(HttpSession session) {
        //清理session
        session.invalidate();
        //返回结果
        return ResultInfo.success();
    }


    // 员工列表
    @GetMapping("/employee/find")
    public ResultInfo findList(String name) { // 接收请求参数
        // 调用service查询
        List<Employee> employeeList = employeeService.findList(name);
        // 封装到resultInfo返回
        return ResultInfo.success(employeeList);
    }

    //新增员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {//接收请求参数
        //调用service添加员工
        employeeService.save(employee);
        //添加成功,返回成功信息,不用返回值
        return ResultInfo.success();
    }

    //编辑修改之前前 回显
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable long id) {//接收路径参数
        //调用service根据id查询
        Employee employee = employeeService.findById(id);
        //修改成功 返回结果
        return ResultInfo.success(employee);
    }

    //修改(新增和修改使用的是同一段前端代码，他会根据跳转到当前页面时，路径上是否含有id参数判断是否是修改)
    @PutMapping("/employee")
    public ResultInfo updateById(@RequestBody Employee employee){//接收参数
        //调用service
        employeeService.updateById(employee);
        //修改成功返回结果
        return ResultInfo.success();
    }
}

